using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Sherwood.Content.DO.Model;
using Xtensive.Storage;
using Record = Sherwood.Content.DO.Model.Record;

namespace Sherwood.Content.DO.Services
{
    public class RecordRepository : IRecordRepository<Record>
    {
        /// <inheritdoc/>
        public Record this[Guid id]
        {
            get { return GetById(id); }
        }

        /// <inheritdoc/>
        public IQueryable<Record> All
        {
            get { return Query.All<Record>(); }
        }

        /// <inheritdoc/>
        public IQueryable<Record> GetByClientId(string clientId)
        {
            return Query.All<Record>().Where(r => r.Client.Id == clientId);
        }

        /// <inheritdoc/>
        public Record GetByReferenceId(string clientId, string referenceId)
        {
            return Query.All<Record>().Where(r => r.Client.Id == clientId && r.ReferenceId == referenceId).FirstOrDefault();
        }

        /// <inheritdoc/>
        public Record GetById(Guid id)
        {
            return Query.All<Record>().Where(r => r.Id == id).FirstOrDefault();
        }

        /// <inheritdoc/>
        public Record Create(IClient client, string referenceId, string title)
        {
            return new Record((Client) client, referenceId, title);
        }

        /// <inheritdoc/>
        public IQueryable<Record> GetByIds(IEnumerable<Guid> recordIds)
        {
            return Query.All<Record>().Where(r => r.Id.In(recordIds));
        }

        public void Delete(Record record)
        {
            record.Remove();
        }
    }
}